<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="高并发," />










<meta name="description" content="前言JDK8的新特性真的是非常多，今天看到一个特别好用的并发工具类CompletableFuture，学会了这个可以说多线程代码是非常好写了，于是学习了一下，这边跟随B站上一个宝藏博主的视频学习，点击宝藏博主链接可以直达他的主页。 下面主要以CompletableFuture的几个API结合各种场景展开。  工具类我们在看下面代码前先看一下工具类的作用 1234567891011121314151">
<meta property="og:type" content="article">
<meta property="og:title" content="CompletableFuture学习笔记">
<meta property="og:url" content="http://yoursite.com/p/5c25cfdb.html">
<meta property="og:site_name" content="Molzhao">
<meta property="og:description" content="前言JDK8的新特性真的是非常多，今天看到一个特别好用的并发工具类CompletableFuture，学会了这个可以说多线程代码是非常好写了，于是学习了一下，这边跟随B站上一个宝藏博主的视频学习，点击宝藏博主链接可以直达他的主页。 下面主要以CompletableFuture的几个API结合各种场景展开。  工具类我们在看下面代码前先看一下工具类的作用 1234567891011121314151">
<meta property="article:published_time" content="2021-06-27T15:23:00.000Z">
<meta property="article:modified_time" content="2021-06-29T16:36:26.385Z">
<meta property="article:author" content="MolZhao">
<meta property="article:tag" content="高并发">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"我们没有找到任何搜索结果: ${query}","hits_stats":"找到约${hits}条结果 (用时 ${time}ms)"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/p/5c25cfdb.html"/>





  <title>CompletableFuture学习笔记 | Molzhao</title>
  








<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Molzhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>

                

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/p/5c25cfdb.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="MolZhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Molzhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">CompletableFuture学习笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-06-27T23:23:00+08:00">
                2021-06-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%A4%9A%E7%BA%BF%E7%A8%8B/index.html" itemprop="url" rel="index">
                    <span itemprop="name">多线程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/p/5c25cfdb.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/p/5c25cfdb.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.4k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  23 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>JDK8的新特性真的是非常多，今天看到一个特别好用的并发工具类<code>CompletableFuture</code>，学会了这个可以说多线程代码是非常好写了，于是学习了一下，这边跟随B站上一个<a href="https://space.bilibili.com/51950540?spm_id_from=333.788.b_765f7570696e666f.1" target="_blank" rel="noopener">宝藏博主</a>的视频学习，点击宝藏博主链接可以直达他的主页。</p>
<p>下面主要以<code>CompletableFuture</code>的几个API结合各种场景展开。</p>
<hr>
<h2 id="工具类"><a href="#工具类" class="headerlink" title="工具类"></a>工具类</h2><p>我们在看下面代码前先看一下工具类的作用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommonUtil</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">CommonUtil</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 耗时</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">timeCost</span><span class="params">(<span class="keyword">long</span> millis)</span> </span>&#123;</span><br><span class="line">        ThreadUtil.sleep(millis);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建耗时行为</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">createBehavior</span><span class="params">(String behavior, <span class="keyword">long</span> millis)</span> </span>&#123;</span><br><span class="line">        System.out.println(String.join(StrPool.DASHED, String.valueOf(System.currentTimeMillis()), String.valueOf(Thread.currentThread().getId()),</span><br><span class="line">                String.valueOf(Thread.currentThread().getName()), behavior));</span><br><span class="line">        timeCost(millis);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建行为</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">createBehavior</span><span class="params">(String behavior)</span> </span>&#123;</span><br><span class="line">        System.out.println(String.join(StrPool.DASHED, String.valueOf(System.currentTimeMillis()), String.valueOf(Thread.currentThread().getId()),</span><br><span class="line">                String.valueOf(Thread.currentThread().getName()), behavior));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="SupplyAsync"><a href="#SupplyAsync" class="headerlink" title="SupplyAsync"></a>SupplyAsync</h2><p><strong>场景：</strong><br>小明进门点菜，点完菜之后厨师开始做菜，同时小明打王者进行等待,等厨师做完菜之后小明开始吃饭。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OpenAsync</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明进门"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明点了 番茄炒蛋 + 饭"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; future = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"厨师做菜"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"番茄炒鸡蛋"</span>;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明玩王者"</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明吃%s"</span>, future.join()));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1624810471194-1-main-小明进门</span><br><span class="line">1624810471194-1-main-小明点了 番茄炒蛋 + 饭</span><br><span class="line">1624810471239-1-main-小明玩王者</span><br><span class="line">1624810471239-11-ForkJoinPool.commonPool-worker-1-厨师做菜</span><br><span class="line">1624810472253-1-main-小明吃番茄炒鸡蛋</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="Compose"><a href="#Compose" class="headerlink" title="Compose"></a>Compose</h2><p><strong>场景：</strong><br>小明进门点菜，这时厨师开始做菜，等做完菜之后需要服务员打饭，在此期间小明可以玩王者等待，等到服务员打饭成功后，小明开始吃饭。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Compose</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明进门"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明点了 番茄炒蛋 + 饭"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; order = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"厨师做菜"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"番茄炒蛋"</span>;</span><br><span class="line">        &#125;).thenCompose(dish -&gt; CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员打饭"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> dish + <span class="string">" + 饭"</span>;</span><br><span class="line">        &#125;));</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明打王者"</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明吃%s"</span>, order.join()));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">1624810596064-1-main-小明进门</span><br><span class="line">1624810596065-1-main-小明点了 番茄炒蛋 + 饭</span><br><span class="line">1624810596112-11-ForkJoinPool.commonPool-worker-1-厨师做菜</span><br><span class="line">1624810596113-1-main-小明打王者</span><br><span class="line">1624810597117-13-ForkJoinPool.commonPool-worker-2-服务员打饭</span><br><span class="line">1624810598135-1-main-小明吃番茄炒蛋 + 饭</span><br></pre></td></tr></table></figure>
<p><code>thenCompose</code>方法的结果是上一个任务的跑完之后把结果交给下一个异步任务也就是说上一个异步任务跑完之后才会开启下一个异步任务。</p>
<hr>
<h2 id="Combine"><a href="#Combine" class="headerlink" title="Combine"></a>Combine</h2><p><strong>场景：</strong><br>小明进门点菜，这时饭店饭还没蒸好，所以厨师开始做菜的同时，服务员需要开始蒸饭，小明打王者等待等到厨师和服务员,蒸完饭做完菜，并且服务员打完饭，小明开始吃饭。</p>
<p>我们使用之前的学过的知识也可以做到</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">other</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明进门"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明点了番茄炒蛋"</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; dish = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"厨师做菜"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"番茄炒蛋"</span>;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; rice = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员蒸饭"</span>, <span class="number">2000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"饭"</span>;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明打王者"</span>);</span><br><span class="line">        String order = String.format(<span class="string">"%s + %s"</span>, dish.join(), rice.join());</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"服务员打饭"</span>, <span class="number">1000</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明吃%s"</span>, order));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">1624810758571-1-main-小明进门</span><br><span class="line">1624810758571-1-main-小明点了番茄炒蛋</span><br><span class="line">1624810758618-11-ForkJoinPool.commonPool-worker-1-厨师做菜</span><br><span class="line">1624810758618-1-main-小明打王者</span><br><span class="line">1624810758619-12-ForkJoinPool.commonPool-worker-2-服务员蒸饭</span><br><span class="line">1624810760642-1-main-服务员打饭</span><br><span class="line">1624810761646-1-main-小明吃番茄炒蛋 + 饭</span><br></pre></td></tr></table></figure>

<p>但是相对来说代码不够优雅，这边有更好的API让代码变得更加优雅。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明进门"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明点了番茄炒蛋"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; order = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"厨师做菜"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"番茄炒蛋"</span>;</span><br><span class="line">        &#125;).thenCombine(CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员蒸饭"</span>, <span class="number">2000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"饭"</span>;</span><br><span class="line">        &#125;), (dish, rice) -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员打饭"</span>, <span class="number">10</span>);</span><br><span class="line">            <span class="keyword">return</span> dish + <span class="string">" + "</span> + rice;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明打王者"</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明吃%s"</span>, order.join()));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">1624810821940-1-main-小明进门</span><br><span class="line">1624810821941-1-main-小明点了番茄炒蛋</span><br><span class="line">1624810821986-11-ForkJoinPool.commonPool-worker-1-厨师做菜</span><br><span class="line">1624810821986-12-ForkJoinPool.commonPool-worker-2-服务员蒸饭</span><br><span class="line">1624810821987-1-main-小明打王者</span><br><span class="line">1624810823990-12-ForkJoinPool.commonPool-worker-2-服务员打饭</span><br><span class="line">1624810824017-1-main-小明吃番茄炒蛋 + 饭</span><br></pre></td></tr></table></figure>
<p><code>thenCombine</code>的作用就是等两个任务都执行完之后得到两个结果，再把两个结果加工成一个结果。</p>
<hr>
<h2 id="Apply"><a href="#Apply" class="headerlink" title="Apply"></a>Apply</h2><p><strong>场景：</strong><br>小明买单，把钱付给服务员并要求开发票，服务员收到款之后就去开发票，同时小明也没有闲着，接了个电话准备回去开黑，刚接完电话服务员就过来，于是小明就走出餐厅，准备回家。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Apply</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 小明和服务员分别在不同的两个线程</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明吃好了"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明 结账、要求发票"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; invoice = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员收款 500元"</span>, <span class="number">100</span>);</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员开发票 面额 500元"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"500元发票"</span>;</span><br><span class="line">        &#125;);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明接到朋友电话，想一起打游戏"</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明拿到%s,准备回家"</span>, invoice.join()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 如果要求收款和开发票的两个服务员不在同一个线程，我们如何实现</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明吃好了"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明 结账、要求发票"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; invoice = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员收款 500元"</span>, <span class="number">100</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            CompletableFuture&lt;String&gt; waiter2 = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">                CommonUtil.createBehavior(<span class="string">"服务员开发票 面额 500元"</span>, <span class="number">1000</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="string">"500元发票"</span>;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> waiter2.join();</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明接到朋友电话，想一起打游戏"</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明拿到%s,准备回家"</span>, invoice.join()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 上面两种方法两个操作都放在同一代码块中，两个服务员也都放在同一代码块中，如果我们</span></span><br><span class="line"><span class="comment">     * 要修改其中一段逻辑就会影响另一段逻辑这是十分不好的。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明吃好了"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明 结账、要求发票"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; invoice = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员收款 500元"</span>, <span class="number">100</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"500"</span>;</span><br><span class="line">        &#125;).thenApply(money -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(String.format(<span class="string">"服务员开发票 面额 %s"</span>, money), <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> String.format(<span class="string">"%s元发票"</span>, money);</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明接到朋友电话，想一起打游戏"</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明拿到%s,准备回家"</span>, invoice.join()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 我们发现上面这种写法开发票和收款是同一个服务员，也就是在同一个线程，如果我们要两个服务员操作,我们怎么办</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * 这里两个线程我这边展示出来是一个线程，是因为线程间调度判断上个线程已经空闲了就直接复用了.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method4</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明吃好了"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明 结账、要求发票"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; invoice = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员收款 500元"</span>, <span class="number">2000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"500"</span>;</span><br><span class="line">        &#125;).thenApplyAsync(money -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(String.format(<span class="string">"服务员开发票 面额 %s"</span>, money), <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> String.format(<span class="string">"%s元发票"</span>, money);</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明接到朋友电话，想一起打游戏"</span>);</span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"小明拿到%s,准备回家"</span>, invoice.join()));</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        method1();</span><br><span class="line">        System.out.println(<span class="string">"-----------------------------"</span>);</span><br><span class="line">        method2();</span><br><span class="line">        System.out.println(<span class="string">"-----------------------------"</span>);</span><br><span class="line">        method3();</span><br><span class="line">        System.out.println(<span class="string">"-----------------------------"</span>);</span><br><span class="line">        method4();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">1624810955359-1-main-小明吃好了</span><br><span class="line">1624810955359-1-main-小明 结账、要求发票</span><br><span class="line">1624810955405-1-main-小明接到朋友电话，想一起打游戏</span><br><span class="line">1624810955405-11-ForkJoinPool.commonPool-worker-1-服务员收款 500元</span><br><span class="line">1624810955512-11-ForkJoinPool.commonPool-worker-1-服务员开发票 面额 500元</span><br><span class="line">1624810956534-1-main-小明拿到500元发票,准备回家</span><br><span class="line">-----------------------------</span><br><span class="line">1624810956534-1-main-小明吃好了</span><br><span class="line">1624810956534-1-main-小明 结账、要求发票</span><br><span class="line">1624810956534-1-main-小明接到朋友电话，想一起打游戏</span><br><span class="line">1624810956534-11-ForkJoinPool.commonPool-worker-1-服务员收款 500元</span><br><span class="line">1624810956636-13-ForkJoinPool.commonPool-worker-2-服务员开发票 面额 500元</span><br><span class="line">1624810957639-1-main-小明拿到500元发票,准备回家</span><br><span class="line">-----------------------------</span><br><span class="line">1624810957639-1-main-小明吃好了</span><br><span class="line">1624810957639-1-main-小明 结账、要求发票</span><br><span class="line">1624810957640-11-ForkJoinPool.commonPool-worker-1-服务员收款 500元</span><br><span class="line">1624810957641-1-main-小明接到朋友电话，想一起打游戏</span><br><span class="line">1624810957745-11-ForkJoinPool.commonPool-worker-1-服务员开发票 面额 500</span><br><span class="line">1624810958751-1-main-小明拿到500元发票,准备回家</span><br><span class="line">-----------------------------</span><br><span class="line">1624810958751-1-main-小明吃好了</span><br><span class="line">1624810958751-1-main-小明 结账、要求发票</span><br><span class="line">1624810958752-11-ForkJoinPool.commonPool-worker-1-服务员收款 500元</span><br><span class="line">1624810958752-1-main-小明接到朋友电话，想一起打游戏</span><br><span class="line">1624810960755-11-ForkJoinPool.commonPool-worker-1-服务员开发票 面额 500</span><br><span class="line">1624810961758-1-main-小明拿到500元发票,准备回家</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="ApplyToEither"><a href="#ApplyToEither" class="headerlink" title="ApplyToEither"></a>ApplyToEither</h2><p><strong>场景：</strong><br>小明走出餐厅，到公交站，现在两个公交车都能回家一个700路一个800路。现在小明是哪路先来就做哪路，用代码如何描述。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ApplyToEither</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明走出餐厅， 来到公交站"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"等待 700路 或者 800路 公交到来"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; bus = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"700路公交车正在赶来。。"</span>, <span class="number">2000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"700路公交到了"</span>;</span><br><span class="line">        &#125;).applyToEither(CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"800路公交车正在赶来。。"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"800路公交到了"</span>;</span><br><span class="line">        &#125;), first -&gt; first);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"%s,小明坐车回家"</span>, bus.join()));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1624811044152-1-main-小明走出餐厅， 来到公交站</span><br><span class="line">1624811044153-1-main-等待 700路 或者 800路 公交到来</span><br><span class="line">1624811044197-11-ForkJoinPool.commonPool-worker-1-700路公交车正在赶来。。</span><br><span class="line">1624811044197-12-ForkJoinPool.commonPool-worker-2-800路公交车正在赶来。。</span><br><span class="line">1624811045212-1-main-800路公交到了,小明坐车回家</span><br></pre></td></tr></table></figure>
<p><code>applyToEither</code>的作用就是上个任务和这个任务一起运行，那个先运行结束，就把任务结果交给Function。</p>
<hr>
<h2 id="Exceptionally"><a href="#Exceptionally" class="headerlink" title="Exceptionally"></a>Exceptionally</h2><p><strong>场景：</strong><br>小明做800路公交回家，又拿起了电话和朋友聊起了游戏，这时候公交撞大树了，这时小明打滴滴回家。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Exceptionally</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明走出餐厅， 来到公交站"</span>);</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"等待 700路 或者 800路 公交到来"</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture&lt;String&gt; bus = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"700路公交车正在赶来。。"</span>, <span class="number">2000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"700路公交到了"</span>;</span><br><span class="line">        &#125;).applyToEither(CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"800路公交车正在赶来。。"</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"800路公交到了"</span>;</span><br><span class="line">        &#125;), first -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(first);</span><br><span class="line">            <span class="keyword">if</span> (first.startsWith(<span class="string">"800"</span>)) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"撞树了。。"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> first;</span><br><span class="line">        &#125;).exceptionally(e -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(e.getMessage());</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"小明叫滴滴"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"滴滴叫到了"</span>;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(String.format(<span class="string">"%s,小明坐车回家"</span>, bus.join()));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">1624811127907-1-main-小明走出餐厅， 来到公交站</span><br><span class="line">1624811127908-1-main-等待 700路 或者 800路 公交到来</span><br><span class="line">1624811127961-11-ForkJoinPool.commonPool-worker-1-700路公交车正在赶来。。</span><br><span class="line">1624811127961-12-ForkJoinPool.commonPool-worker-2-800路公交车正在赶来。。</span><br><span class="line">1624811128969-12-ForkJoinPool.commonPool-worker-2-800路公交到了</span><br><span class="line">1624811128970-12-ForkJoinPool.commonPool-worker-2-java.lang.RuntimeException: 撞树了。。</span><br><span class="line">1624811128970-12-ForkJoinPool.commonPool-worker-2-小明叫滴滴</span><br><span class="line">1624811128978-1-main-滴滴叫到了,小明坐车回家</span><br></pre></td></tr></table></figure>
<p><code>exceptionally</code>就是遇到异常之后，小明处理异常的步骤，exceptionally当然不只可以加在尾部还能在上面的链式中任何一步加。相比于<code>try-catch</code>块来说真的简洁不少。</p>
<hr>
<h2 id="扩展"><a href="#扩展" class="headerlink" title="扩展"></a>扩展</h2><p>在上面我们学了6个API。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># supplyAsync   用来开启异步任务</span></span><br><span class="line"><span class="comment"># thenCompose   用来连接两个异步任务</span></span><br><span class="line"><span class="comment"># thenCombine   用来合并两个异步任务</span></span><br><span class="line"><span class="comment"># thenApply     用来做任务的后置处理</span></span><br><span class="line"><span class="comment"># applyToEither 用来获取最先完成的异步任务</span></span><br><span class="line"><span class="comment"># exceptionally 用来处理异常</span></span><br></pre></td></tr></table></figure>

<p>以上6个API大部分都满足下面三个规则：</p>
<ul>
<li>xxx(arg)</li>
<li>xxxAsync(arg)</li>
<li>xxxAsync(arg,Executor)</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">CompletableFuture&lt;String&gt; invoice = CompletableFuture.supplyAsync(() -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(<span class="string">"服务员收款 500元"</span>, <span class="number">100</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"500"</span>;</span><br><span class="line">        &#125;).thenApply(money -&gt; &#123;</span><br><span class="line">            CommonUtil.createBehavior(String.format(<span class="string">"服务员开发票 面额 %s"</span>, money), <span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">return</span> String.format(<span class="string">"%s元发票"</span>, money);</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>
<p><code>Apply</code>方法就是上一个任务执行完之后去执行下一个任务，<code>supplyAsync</code>和<code>thenApply</code>中的代码都在同一个线程里运行，<code>thenApply</code>就是把后面的代码块放在上面同一个代码块里的去运行，<code>CompletableFuture</code>会把这两个代码封装成一个任务去运行，随意这两个代码在一个线程里运行。当调用<code>thenApplyAsync</code>方法<code>CompletableFuture</code>就会把这两块代码看成是独立的两个任务。我们明白了<code>thenApply</code>和<code>thenApplyAsync</code>的区别，那另外的也是一样的。</p>
<p>由于<code>CompletableFuture</code>存在线程的复用，我们不能只观察线程的ID来判断。</p>
<h3 id="类似方法比较"><a href="#类似方法比较" class="headerlink" title="类似方法比较"></a>类似方法比较</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># supplyAsync 开启异步任务且提供返回值</span></span><br><span class="line"><span class="comment"># runAsync    开启异步任务没有返回值</span></span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># thenApply  接收前面任务参数且有返回值</span></span><br><span class="line"><span class="comment"># thenRun    不接收前面任务参数，且没有返回值</span></span><br><span class="line"><span class="comment"># thenAccept 接收前面任务参数但是没有返回值</span></span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># thenCombine      接收前面两个任务任务参数且有返回值</span></span><br><span class="line"><span class="comment"># thenAcceptBoth   内部消化前两个任务的结果，没有返回值</span></span><br><span class="line"><span class="comment"># thenRunAfterBoth 不关心前两个任务的结果且没有返回值</span></span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># applyToEither  会得到最快执行完任务的结果，有返回值</span></span><br><span class="line"><span class="comment"># AcceptEither   会得到最快执行完任务的结果，没有返回值</span></span><br><span class="line"><span class="comment"># RunAfterEither 既不关心最快执行完任务的结果，也没有返回值</span></span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># exceptionally 处理前面任务的异常并且修正成一个正常值</span></span><br><span class="line"><span class="comment"># handle        如果前面的程序正常执行就会收到正常执行的结果，如果前面程序异常就会接收到异常，无论前面正常或者异常，handle方法都会返回一个结果让后面程序继续执行</span></span><br><span class="line"><span class="comment"># whenComplete  和handle的区别是没有返回值</span></span><br></pre></td></tr></table></figure>
<hr>
<h2 id="性能问题"><a href="#性能问题" class="headerlink" title="性能问题"></a>性能问题</h2><h3 id="任务巨多，如何保证性能？"><a href="#任务巨多，如何保证性能？" class="headerlink" title="任务巨多，如何保证性能？"></a>任务巨多，如何保证性能？</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TerribleCode</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明和小伙伴们 进餐厅点菜"</span>);</span><br><span class="line">        <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        ArrayList&lt;Dish&gt; dishes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">7</span>; i++) &#123;</span><br><span class="line">            dishes.add(<span class="keyword">new</span> Dish(<span class="string">"菜"</span> + i, <span class="number">1</span>));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        dishes.forEach(dish -&gt; CompletableFuture.runAsync(dish::make).join());</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"菜都做好了，上桌"</span> + (System.currentTimeMillis() - startTime));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">1624982786532-1-main-小明和小伙伴们 进餐厅点菜</span><br><span class="line">1624982786581-11-ForkJoinPool.commonPool-worker-1-菜0制作完毕，来吃我把</span><br><span class="line">1624982787588-11-ForkJoinPool.commonPool-worker-1-菜1制作完毕，来吃我把</span><br><span class="line">1624982788588-11-ForkJoinPool.commonPool-worker-1-菜2制作完毕，来吃我把</span><br><span class="line">1624982789589-11-ForkJoinPool.commonPool-worker-1-菜3制作完毕，来吃我把</span><br><span class="line">1624982790593-11-ForkJoinPool.commonPool-worker-1-菜4制作完毕，来吃我把</span><br><span class="line">1624982791596-11-ForkJoinPool.commonPool-worker-1-菜5制作完毕，来吃我把</span><br><span class="line">1624982792599-11-ForkJoinPool.commonPool-worker-1-菜6制作完毕，来吃我把</span><br><span class="line">1624982793600-1-main-菜都做好了，上桌7068</span><br></pre></td></tr></table></figure>
<p>由于制作一盆菜需要1S所以七盘菜需要7S，硬生生把多线程写成了单线程还不如直接放在main线程中直接执行七次。直接把异步变成了串行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TerribleCodeImprove</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明和小伙伴们 进餐厅点菜"</span>);</span><br><span class="line">        <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        ArrayList&lt;Dish&gt; dishes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">7</span>; i++) &#123;</span><br><span class="line">            dishes.add(<span class="keyword">new</span> Dish(<span class="string">"菜"</span> + i, <span class="number">1</span>));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 做菜</span></span><br><span class="line">        ArrayList&lt;CompletableFuture&gt; cfList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        dishes.forEach(dish -&gt; cfList.add(CompletableFuture.runAsync(dish::make)));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 等待所有任务执行完毕</span></span><br><span class="line">        CompletableFuture.allOf(cfList.toArray(<span class="keyword">new</span> CompletableFuture[cfList.size()])).join();</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"菜都做好了，上桌"</span> + (System.currentTimeMillis() - startTime));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">1624982458305-1-main-小明和小伙伴们 进餐厅点菜</span><br><span class="line">1624982458355-11-ForkJoinPool.commonPool-worker-1-菜0制作完毕，来吃我把</span><br><span class="line">1624982458355-12-ForkJoinPool.commonPool-worker-2-菜1制作完毕，来吃我把</span><br><span class="line">1624982458355-13-ForkJoinPool.commonPool-worker-3-菜2制作完毕，来吃我把</span><br><span class="line">1624982458355-14-ForkJoinPool.commonPool-worker-4-菜3制作完毕，来吃我把</span><br><span class="line">1624982458355-16-ForkJoinPool.commonPool-worker-6-菜5制作完毕，来吃我把</span><br><span class="line">1624982458355-15-ForkJoinPool.commonPool-worker-5-菜4制作完毕，来吃我把</span><br><span class="line">1624982458355-17-ForkJoinPool.commonPool-worker-7-菜6制作完毕，来吃我把</span><br><span class="line">1624982459359-1-main-菜都做好了，上桌1054</span><br></pre></td></tr></table></figure>
<p>这时我们发现七盘菜1S就做好了，那同时执行的线程能有多少个呢，我们只需要每次都多加一盘菜，什么时候发现执行的时间要之前的两倍就知道同时能执行多少个线程了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明和小伙伴们 进餐厅点菜"</span>);</span><br><span class="line">        <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        CompletableFuture[] dishes = IntStream.rangeClosed(<span class="number">0</span>, <span class="number">7</span>)</span><br><span class="line">                .mapToObj(i -&gt; <span class="keyword">new</span> Dish(<span class="string">"菜"</span> + i, <span class="number">1</span>))</span><br><span class="line">                .map(dish -&gt; CompletableFuture.runAsync(dish::make))</span><br><span class="line">                .toArray(CompletableFuture[]::<span class="keyword">new</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 等待所有任务执行完毕</span></span><br><span class="line">        CompletableFuture.allOf(dishes).join();</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"菜都做好了，上桌"</span> + (System.currentTimeMillis() - startTime));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">1624982828176-1-main-小明和小伙伴们 进餐厅点菜</span><br><span class="line">1624982828250-11-ForkJoinPool.commonPool-worker-1-菜0制作完毕，来吃我把</span><br><span class="line">1624982828250-12-ForkJoinPool.commonPool-worker-2-菜1制作完毕，来吃我把</span><br><span class="line">1624982828250-13-ForkJoinPool.commonPool-worker-3-菜2制作完毕，来吃我把</span><br><span class="line">1624982828250-15-ForkJoinPool.commonPool-worker-5-菜4制作完毕，来吃我把</span><br><span class="line">1624982828251-16-ForkJoinPool.commonPool-worker-6-菜5制作完毕，来吃我把</span><br><span class="line">1624982828251-14-ForkJoinPool.commonPool-worker-4-菜3制作完毕，来吃我把</span><br><span class="line">1624982828251-17-ForkJoinPool.commonPool-worker-7-菜6制作完毕，来吃我把</span><br><span class="line">1624982829256-15-ForkJoinPool.commonPool-worker-5-菜7制作完毕，来吃我把</span><br><span class="line">1624982830258-1-main-菜都做好了，上桌2082</span><br></pre></td></tr></table></figure>
<p>我们发现在第八盘菜的时候就需要2S了那这个8这个数从哪里来的呢，然后JDK开发人员就写死了8把，显然是不可能的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommonPoolSize</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// CPU核心数 - 8</span></span><br><span class="line">        System.out.println(Runtime.getRuntime().availableProcessors());</span><br><span class="line">        <span class="comment">// 当前线程数 - 0</span></span><br><span class="line">        System.out.println(ForkJoinPool.commonPool().getPoolSize());</span><br><span class="line">        <span class="comment">// 最大线程数 - 7</span></span><br><span class="line">        System.out.println(ForkJoinPool.commonPool().getParallelism());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这边我这台电脑是4核8线程的CPU，也就是说我这台电脑能同时运行八个任务，上面的7就是通过8-1得到的。如果你的处理器支持超线程的话就要用线程数去减了得到的结果就是<code>CompletableFuture</code>底层用到的线程池的最大线程数。</p>
<p>我们想在知道只要任务大于7就是大量任务了，假如我们项目中很多时候任务数量都是大于7的，那我们只要修改线程池的最大线程数不久好了吗，我们只需要在线程池初始化之前改掉最大线程数就好了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodCode</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 或者启动参数-Djava.util.concurrent.ForkJoinPool.common.parallelism=8</span></span><br><span class="line">        System.setProperty(<span class="string">"java.util.concurrent.ForkJoinPool.common.parallelism"</span>, <span class="string">"8"</span>);</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明和小伙伴们 进餐厅点菜"</span>);</span><br><span class="line">        <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        CompletableFuture[] dishes = IntStream.rangeClosed(<span class="number">0</span>, <span class="number">7</span>)</span><br><span class="line">                .mapToObj(i -&gt; <span class="keyword">new</span> Dish(<span class="string">"菜"</span> + i, <span class="number">1</span>))</span><br><span class="line">                .map(dish -&gt; CompletableFuture.runAsync(dish::make))</span><br><span class="line">                .toArray(CompletableFuture[]::<span class="keyword">new</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 等待所有任务执行完毕</span></span><br><span class="line">        CompletableFuture.allOf(dishes).join();</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"菜都做好了，上桌"</span> + (System.currentTimeMillis() - startTime));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">1624983453369-1-main-小明和小伙伴们 进餐厅点菜</span><br><span class="line">1624983453422-11-ForkJoinPool.commonPool-worker-1-菜0制作完毕，来吃我把</span><br><span class="line">1624983453423-12-ForkJoinPool.commonPool-worker-2-菜1制作完毕，来吃我把</span><br><span class="line">1624983453423-14-ForkJoinPool.commonPool-worker-4-菜3制作完毕，来吃我把</span><br><span class="line">1624983453423-13-ForkJoinPool.commonPool-worker-3-菜2制作完毕，来吃我把</span><br><span class="line">1624983453423-16-ForkJoinPool.commonPool-worker-6-菜5制作完毕，来吃我把</span><br><span class="line">1624983453423-17-ForkJoinPool.commonPool-worker-7-菜6制作完毕，来吃我把</span><br><span class="line">1624983453423-15-ForkJoinPool.commonPool-worker-5-菜4制作完毕，来吃我把</span><br><span class="line">1624983453423-18-ForkJoinPool.commonPool-worker-0-菜7制作完毕，来吃我把</span><br><span class="line">1624983454429-1-main-菜都做好了，上桌1060</span><br></pre></td></tr></table></figure>
<p>我们发现现在8盘菜只需要1S就做好了,把线程数设置一个合适的数值就能调整性能了。这个CommonPool不单单给CF使用，所以我们在开发中需要创建一个自定义的线程池来给CF使用。方便控制且互不影响。</p>
<p>我们也可以根据任务数量动态创建自定义线程池，当任务来了就创建线程池，当执行完之后再把线程池给销毁。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomThreadPool</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ExecutorService executorService = Executors.newCachedThreadPool();</span><br><span class="line"></span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"小明和小伙伴们 进餐厅点菜"</span>);</span><br><span class="line">        <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        CompletableFuture[] dishes = IntStream.rangeClosed(<span class="number">0</span>, <span class="number">99</span>)</span><br><span class="line">                .mapToObj(i -&gt; <span class="keyword">new</span> Dish(<span class="string">"菜"</span> + i, <span class="number">1</span>))</span><br><span class="line">                .map(dish -&gt; CompletableFuture.runAsync(dish::make, executorService))</span><br><span class="line">                .toArray(CompletableFuture[]::<span class="keyword">new</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 等待所有任务执行完毕</span></span><br><span class="line">        CompletableFuture.allOf(dishes).join();</span><br><span class="line">        CommonUtil.createBehavior(<span class="string">"菜都做好了，上桌"</span> + (System.currentTimeMillis() - startTime));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">1624983798696-101-pool-1-thread-91-菜90制作完毕，来吃我把</span><br><span class="line">1624983798696-102-pool-1-thread-92-菜91制作完毕，来吃我把</span><br><span class="line">1624983798696-103-pool-1-thread-93-菜92制作完毕，来吃我把</span><br><span class="line">1624983798697-104-pool-1-thread-94-菜93制作完毕，来吃我把</span><br><span class="line">1624983798697-105-pool-1-thread-95-菜94制作完毕，来吃我把</span><br><span class="line">1624983798697-106-pool-1-thread-96-菜95制作完毕，来吃我把</span><br><span class="line">1624983798697-107-pool-1-thread-97-菜96制作完毕，来吃我把</span><br><span class="line">1624983798697-108-pool-1-thread-98-菜97制作完毕，来吃我把</span><br><span class="line">1624983798697-109-pool-1-thread-99-菜98制作完毕，来吃我把</span><br><span class="line">1624983798697-110-pool-1-thread-100-菜99制作完毕，来吃我把</span><br><span class="line">1624983799702-1-main-菜都做好了，上桌1070</span><br></pre></td></tr></table></figure>
<p>我们发现创建100到菜也只需要1S，因为<code>newCachedThreadPool</code>可是个大胃王，他能不停的创建线程</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newCachedThreadPool</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">0</span>, Integer.MAX_VALUE,</span><br><span class="line">                                      <span class="number">60L</span>, TimeUnit.SECONDS,</span><br><span class="line">                                      <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;());</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="如何观察任务调度的情况？"><a href="#如何观察任务调度的情况？" class="headerlink" title="如何观察任务调度的情况？"></a>如何观察任务调度的情况？</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 这段代码里有两个异步任务 按道理A和B应该在不同的线程中执行</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThenRunAsyncThreadReuse</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        CompletableFuture.runAsync(() -&gt; CommonUtil.createBehavior(<span class="string">"A"</span>))</span><br><span class="line">                .thenRunAsync(() -&gt; CommonUtil.createBehavior(<span class="string">"B"</span>))</span><br><span class="line">                .join();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1624984232215-11-ForkJoinPool.commonPool-worker-1-A</span><br><span class="line">1624984232215-11-ForkJoinPool.commonPool-worker-1-B</span><br></pre></td></tr></table></figure>
<p>由于A很快就结束了，B一开始就发现有空闲线程，就直接复用A的线程了。也就是A和B在同一个线程中执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DealThenRunAsyncThreadReuse</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 我们把线程的存活时间设置为0，代表这个线程完成任务后就立马销毁掉自己</span></span><br><span class="line">        ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">0</span>, Integer.MAX_VALUE, <span class="number">0</span>, TimeUnit.SECONDS, <span class="keyword">new</span> SynchronousQueue&lt;&gt;());</span><br><span class="line"></span><br><span class="line">        CompletableFuture.runAsync(() -&gt; CommonUtil.createBehavior(<span class="string">"A"</span>), threadPoolExecutor)</span><br><span class="line">                .thenRunAsync(() -&gt; CommonUtil.createBehavior(<span class="string">"B"</span>), threadPoolExecutor)</span><br><span class="line">                .join();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1624984512899-11-pool-1-thread-1-A</span><br><span class="line">1624984512899-12-pool-1-thread-2-B</span><br></pre></td></tr></table></figure>
<p>这样我们发现A和B永远不会在一个线程中运行，注意这种方式只能用于测试和研究不要写到生产环境去。</p>
<p><a href="https://gitee.com/hizyj/complete-future-learning-notes" target="_blank" rel="noopener">点此获取Demo链接</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E9%AB%98%E5%B9%B6%E5%8F%91/index.html" rel="tag"># 高并发</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/p/b2642bd.html" rel="next" title="Mybatis-Plus的一次PR经历-识别表名">
                <i class="fa fa-chevron-left"></i> Mybatis-Plus的一次PR经历-识别表名
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/p/13e68e83.html" rel="prev" title="内网穿透工具 - FRP">
                内网穿透工具 - FRP <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="MolZhao" />
            
              <p class="site-author-name" itemprop="name">MolZhao</p>
              <p class="site-description motion-element" itemprop="description">沉淀</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/index.html">
              
                  <span class="site-state-item-count">54</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/normcorer" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MolZhaovo@163.com" target="_blank" title="Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#工具类"><span class="nav-number">2.</span> <span class="nav-text">工具类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SupplyAsync"><span class="nav-number">3.</span> <span class="nav-text">SupplyAsync</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Compose"><span class="nav-number">4.</span> <span class="nav-text">Compose</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Combine"><span class="nav-number">5.</span> <span class="nav-text">Combine</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Apply"><span class="nav-number">6.</span> <span class="nav-text">Apply</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ApplyToEither"><span class="nav-number">7.</span> <span class="nav-text">ApplyToEither</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Exceptionally"><span class="nav-number">8.</span> <span class="nav-text">Exceptionally</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#扩展"><span class="nav-number">9.</span> <span class="nav-text">扩展</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#类似方法比较"><span class="nav-number">9.1.</span> <span class="nav-text">类似方法比较</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#性能问题"><span class="nav-number">10.</span> <span class="nav-text">性能问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#任务巨多，如何保证性能？"><span class="nav-number">10.1.</span> <span class="nav-text">任务巨多，如何保证性能？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何观察任务调度的情况？"><span class="nav-number">10.2.</span> <span class="nav-text">如何观察任务调度的情况？</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MolZhao</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">ZYJ</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>






        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script type="text/javascript" src="/js/src/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '18BuKzLQMbUp8ECwDBiHu6Df-MdYXbMMI',
        appKey: 'xVTsu5pYLayqSvClr36TzcAH',
        placeholder: '(•̀へ•╮)',
        avatar:'identicon',
        guest_info:guest,
        pageSize:'10' || 10,
    });

    $('.vpower').html('');
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.5,"jsonPath":"/live2dw/assets/assets/wanko.model.json"},"display":{"superSample":2,"width":150,"height":150,"position":"right","hOffset":30,"vOffset":20},"mobile":{"show":false,"scale":0.05},"react":{"opacityDefault":0.6,"opacityOnHover":0.2},"log":false});</script></body>
</html>
